<?php

namespace app\api\model;

use think\Db;
use app\api\model\Common;
use com\verify\JdeVerify;

class User extends Common
{

	/**
	 * 为了数据库的整洁，同时又不影响Model和Controller的名称
	 * 我们约定每个模块的数据表都加上相同的前缀，比如微信模块用weixin作为数据表前缀
	 */
	protected $name = 'admin_user';
	protected $createTime = 'create_time';
	protected $updateTime = false;
	protected $autoWriteTimestamp = true;
	protected $insert = [
		'status' => 1,
	];

	/**
	 * 获取用户所属所有用户组
	 * @param  array   $param  [description]
	 */
	public function groups()
	{
		return $this->belongsToMany('group', '__ADMIN_ACCESS__', 'group_id', 'user_id');
	}

	/**
	 * 获取用户上传的录音文件
	 * 匹配字段:id, formatname, create_time, update_time, lvsr_status
	 */
	public function speechs()
	{
		return $this->hasMany('speech', 'user_id')
			->field('id, user_id, formatname, create_time, update_time, lvsr_status, is_delete');
	}

	/**
	 * [getDataList 列表]
	 * @AuthorHTL
	 * @DateTime  2017-02-10T22:19:57+0800
	 * @param     [string]                   $keywords [关键字]
	 * @param     [number]                   $page     [当前页数]
	 * @param     [number]                   $limit    [t每页数量]
	 * @return    [array]                             [description]
	 */
	public function getDataList($keywords, $page, $limit)
	{
		$map = [];
		if ($keywords) {
			$map['username|realname'] = ['like', '%' . $keywords . '%'];
		}

		// 默认除去超级管理员
		$map['user.id'] = array('neq', 1);
		$dataCount = $this->alias('user')->where($map)->count('id');

		$list = $this
			->where($map)
			->alias('user');
		//->join('__ADMIN_STRUCTURE__ structure', 'structure.id=user.structure_id', 'LEFT')
		//->join('__ADMIN_POST__ post', 'post.id=user.post_id', 'LEFT');

		// 若有分页
		if ($page && $limit) {
			$list = $list->page($page, $limit);
		}

		$list = $list
			->field('user.*')
			->select();

		$data['list'] = $list;
		$data['dataCount'] = $dataCount;

		return $data;
	}

	/**
	 * [getDataById 根据主键获取详情]
	 * @linchuangbin
	 * @DateTime  2017-02-10T21:16:34+0800
	 * @param     string                   $id [主键]
	 * @return    [array]                       
	 */
	public function getDataById($id = '')
	{
		$data = $this->get($id);
		if (!$data) {
			$this->error = '暂无此数据';
			return false;
		}
		$data['groups'] = $this->get($id)->groups;
		return $data;
	}

	public function getDataByPhone($phone = '')
	{
		if (!$phone) {
			$this->error = '手机号有误';
			return false;
		}
		$userInfo = $this->where(['phone' => $phone])->find();
		if (!$userInfo) {
			$this->error = '无此账号,请联系客服！';
			return false;
		}


		if ($userInfo['status'] === 0) {
			$this->error = '帐号已被禁用';
			return false;
		}
		// 获取菜单和权限

		$dataList = $this->getMenuAndRule($userInfo['id']);

		if (!$dataList['menusList']) {
			$this->error = '没有权限';
			return false;
		}

		/* if ($isRemember || $type) {
        	$secret['username'] = $username;
        	$secret['password'] = $password;
        	$data['rememberKey'] = encrypt($secret);
        } */

		// 保存缓存        
		session_start();
		$info['userInfo'] = $userInfo;
		$info['sessionId'] = session_id();
		$userInfo['username'] = $userInfo['phone'];
		$authKey = user_md5($userInfo['username'] . $userInfo['password'] . $info['sessionId'] . date('Ymd', time()));
		$info['_AUTH_LIST_'] = $dataList['rulesList'];
		$info['authKey'] = $authKey;
		cache('Auth_' . $authKey, null);
		cache('Auth_' . $authKey, $info, config('LOGIN_SESSION_VALID'));
		// 返回信息
		$data['authKey']		= $authKey;
		$data['sessionId']		= $info['sessionId'];
		$user['id'] = $userInfo['id'];
		$user['username'] = $userInfo['username'];
		$data['userInfo']		= $user;
		//$data['authList']		= $dataList['rulesList'];
		//$data['menusList']		= $dataList['menusList'];
		return $data;
	}
	/**
	 * 创建用户
	 * @param  array   $param  [description]
	 */
	public function createData($param)
	{
		if (empty($param['groups'])) {
			$this->error = '请至少勾选一个用户组';
			return false;
		}

		// 验证
		$validate = validate($this->name);
		if (!$validate->check($param)) {
			$this->error = $validate->getError();
			return false;
		}

		$this->startTrans();
		try {
			$param['password'] = user_md5($param['password']);
			$this->data($param)->allowField(true)->save();

			foreach ($param['groups'] as $k => $v) {
				$userGroup['user_id'] = $this->id;
				$userGroup['group_id'] = $v;
				$userGroups[] = $userGroup;
			}
			Db::name('admin_access')->insertAll($userGroups);

			$this->commit();
			return true;
		} catch (\Exception $e) {
			$this->rollback();
			$this->error = '添加失败';
			return false;
		}
	}

	/**
	 * 通过id修改用户
	 * @param  array   $param  [description]
	 */
	public function updateDataById($param, $id)
	{
		// 不能操作超级管理员
		if ($id == 1) {
			$this->error = '非法操作';
			return false;
		}
		$checkData = $this->get($id);
		if (!$checkData) {
			$this->error = '暂无此数据';
			return false;
		}

		$this->startTrans();

		try {
			if (!empty($param['password'])) {
				$param['password'] = user_md5($param['password']);
			}
			$this->allowField(true)->save($param, ['id' => $id]);
			$this->commit();
			return true;
		} catch (\Exception $e) {
			$this->rollback();
			$this->error = '编辑失败';
			return false;
		}
	}

	/**
	 * [login 登录]
	 * @AuthorHTL
	 * @DateTime  2017-02-10T22:37:49+0800
	 * @param     [string]                   $u_username [账号]
	 * @param     [string]                   $u_pwd      [密码]
	 * @param     [string]                   $verifyCode [验证码]
	 * @param     Boolean                  	 $isRemember [是否记住密码]
	 * @param     Boolean                    $type       [是否重复登录]
	 * @return    [type]                               [description]
	 */
	public function login($username, $password, $verifyCode = '', $isRemember = false, $type = false)
	{

		if (!$username) {
			$this->error = lang('account_empty');
			return false;
		}
		if (!$password) {
			$this->error = lang('password_empty');
			return false;
		}

		if(!in_array($username, config('huisheng.white_name'))){
			if (config('IDENTIFYING_CODE') && !$type) {
				if (!$verifyCode) {
					$this->error = lang('verification_code_empty');
					return false;
				}
				$captcha = new JdeVerify(config('captcha'));
				//var_dump($verifyCode);
				//var_dump($captcha->check($verifyCode));
				if (!$captcha->check($verifyCode)) {
					$this->error = lang('verification_code_error');
					return false;
				}
			}
		}


		$map['username|phone|email'] = $username;

		$userInfo = $this->where($map)->find();
		if (!$userInfo) {
			$userInfo = $this->where(array('phone' => $username))->find();
			if (!$userInfo) {
				$this->error = lang('account_not_exist');
				return false;
			}
		}

		if (user_md5($password) !== $userInfo['password']) {
			$this->error = lang('password_error');
			return false;
		}
		if ($userInfo['status'] === 0) {
			$this->error = lang('account_disabled');
			return false;
		}

		// 获取菜单和权限
		$dataList = $this->getRule($userInfo['id']);
		if (!$dataList['rulesList']) {
			$this->error = lang('permission_denied');
			return false;
		}
		//}
		$role = [];
		foreach($userInfo->groups as $value){
			$role[] = $value->name;
		}
		//临时添加
		//$role[] = "superadmin";
		if(config('huisheng.CAN_WAVE_JEPG')){
			$role[] = "waver";
		}
		$userInfo->role = $role;


		/*if ($isRemember || $type) {
        	$secret['username'] = $username;
        	$secret['password'] = $password;
        	$data['rememberKey'] = encrypt($secret);
		}*/
		//判断重复登录
		//普通会员 单设备登录
		// if ($userInfo['user_group'] < 18) {
		if (cache('user_' . $userInfo['id'])) {
			$is_set_authkey = cache('user_' . $userInfo['id']);
			if (cache('Auth_' . $is_set_authkey)) {
				cache('Auth_' . $is_set_authkey, null);
			}
		}
		// 保存缓存        
		//session_start();
		$info['userInfo'] = $userInfo;
		$info['sessionId'] = session_id();
		$authKey = user_md5($userInfo['username'] . $userInfo['password'] . $info['sessionId'] . date('Ymd', time()));
		$info['_AUTH_LIST_'] = $dataList['rulesList'];
		cache('Auth_' . $authKey, null);
		$info['authKey'] = $authKey;
		cache('Auth_' . $authKey, $info, config('LOGIN_SESSION_VALID'));
		cache('user_' . $userInfo['id'], $authKey, config('LOGIN_SESSION_VALID'));
		// $authKey = 'c74ee089baa7289794e66bb93c8c5b89';
		// $info['authKey'] = $authKey;
		// cache('Auth_' . $authKey, $info);
		// cache('user_' . $userInfo['id'], $authKey);
		// else{//多设备同时登录 */


		// 返回信息
		/*  $data['authKey']		= $authKey;
		$data['sessionId']		= $info['sessionId'];
		$user['id'] = $userInfo['id'];
		$user['username'] = $userInfo['username'];
		$data['userInfo']		= $user; */
		$data['token']		= $authKey;
		//$data['sessionId']		= $info['sessionId'];
		$data['userId'] = $userInfo['id'];
		$data['username'] = $userInfo['username'];
		$data['nickname'] = $userInfo['nickname'];
		$data['phone'] = $userInfo['phone'];
		$data['email'] = $userInfo['email'];

		$data['authList']		= $dataList['rulesList'];
		//$data['menusList']		= $dataList['menusList'];
		return $data;
	}

	/**
	 * 生成token
	 */
	public function makeToken(){
		$dataList = $this->getRule($this->id);
		$role = [];
		foreach($this->groups as $value){
			$role[] = $value->name;
		}
		$this->role = $role;
		$info['userInfo'] = $this;
		$info['_AUTH_LIST_'] = $dataList['rulesList'];
		$authKey = user_md5($this->username . $this->password . date('Ymd', time()));
		cache('Auth_' . $authKey, null);
		$info['authKey'] = $authKey;
		cache('Auth_' . $authKey, $info, config('LOGIN_SESSION_VALID'));
		cache('user_' . $this->id, $authKey, config('LOGIN_SESSION_VALID'));
		return $authKey;
	}

	/**
	 * 修改密码
	 * @param  array   $param  [description]
	 */
	public function setInfo($auth_key, $old_pwd, $new_pwd)
	{
		$cache = cache('Auth_' . $auth_key);
		if (!$cache) {
			$this->error = lang('log_in_first');
			return false;
		}
		if (!$old_pwd) {
			$this->error = lang('enter_old_password');
			return false;
		}
		if (!$new_pwd) {
			$this->error = lang('enter_new_password');
			return false;
		}
		if ($new_pwd == $old_pwd) {
			$this->error = lang('old_and_new_passwords_not_consistent');
			return false;
		}
		if(!preg_match('/^[a-zA-Z0-9]{4,20}$/', trim($new_pwd))){
			$this->error = lang('new_password_format_error');
			return false;
		}

		$userInfo = $cache['userInfo'];

		$password = $this->where('id', $userInfo['id'])->value('password');
		if (user_md5($old_pwd) != $password) {
			$this->error = lang('original_password_error');
			return false;
		}
		if (user_md5($new_pwd) == $password) {
			$this->error = lang('password_has_not_changed');
			return false;
		}
		if ($this->where('id', $userInfo['id'])->setField('password', user_md5($new_pwd))) {
			$userInfo = $this->where('id', $userInfo['id'])->find();
			$role = [];
			foreach($userInfo->groups as $value){
				$role[] = $value->name;
			}
			$userInfo->role = $role;
			// 重新设置缓存
			session_start();
			$cache['userInfo'] = $userInfo;
			$cache['authKey'] = user_md5($userInfo['username'] . $userInfo['password'] . session_id());
			cache('Auth_' . $auth_key, null);
			cache('Auth_' . $cache['authKey'], $cache, config('LOGIN_SESSION_VALID'));
			return $cache['authKey']; //把auth_key传回给前端
		}

		$this->error = lang('change_failed');
		return false;
	}

	/**
	 * 修改密码
	 * @param  array   $param  [description]
	 */
	public function setPasswd($auth_key, $old_pwd, $new_pwd)
	{
		$cache = cache('Front_' . $auth_key);
		if (!$cache) {
			$this->error = lang('log_in_first');
			return false;
		}
		if (!$old_pwd) {
			$this->error = lang('enter_old_password');
			return false;
		}
		if (!$new_pwd) {
			$this->error = lang('enter_new_password');
			return false;
		}
		if ($new_pwd == $old_pwd) {
			$this->error = lang('old_and_new_passwords_not_consistent');
			return false;
		}
		if(!preg_match('/^[a-zA-Z0-9]{6,12}$/', trim($new_pwd))){
			$this->error = lang('new_password_format_error');
			return false;
		}

		$userInfo = $cache['userInfo'];

		$password = $this->where('id', $userInfo['id'])->value('password');
		if (user_md5($old_pwd) != $password) {
			$this->error = lang('original_password_error');
			return false;
		}
		if (user_md5($new_pwd) == $password) {
			$this->error = lang('password_has_not_changed');
			return false;
		}
		if ($this->where('id', $userInfo['id'])->setField('password', user_md5($new_pwd))) {
			$userInfo = $this->where('id', $userInfo['id'])->find();
			$role = [];
			foreach($userInfo->groups as $value){
				$role[] = $value->name;
			}
			$userInfo->role = $role;
			// 重新设置缓存
			$cache['userInfo'] = $userInfo;
			$cache['authKey'] = user_md5($userInfo['username'] . $userInfo['password'] . date('Ymd', time()));
			cache('Front_' . $auth_key, null);
			cache('Front_' . $cache['authKey'], $cache, 0);
			cache('person_' . $userInfo['id'], $cache['authKey'], 0);
			return $cache['authKey']; //把auth_key传回给前端
		}

		$this->error = lang('change_failed');
		return false;
	}	

	/**
	 * 获取菜单和权限
	 * @param  array   $param  [description]
	 */
	protected function getMenuAndRule($u_id)
	{
		if ($u_id === 1) {
			$map['status'] = 1;
			$menusList = Db::name('admin_menu')->where($map)->order('sort asc')->select();
		} else {
			$groups = $this->get($u_id)->groups;
			$ruleIds = [];
			foreach ($groups as $k => $v) {
				$ruleIds = array_unique(array_merge($ruleIds, explode(',', $v['rules'])));
			}

			$ruleMap['id'] = array('in', $ruleIds);
			$ruleMap['status'] = 1;
			// 重新设置ruleIds，除去部分已删除或禁用的权限。
			$rules = Db::name('admin_rule')->where($ruleMap)->select();
			foreach ($rules as $k => $v) {
				$ruleIds[] = $v['id'];
				$rules[$k]['name'] = strtolower($v['name']);
			}
			empty($ruleIds) && $ruleIds = '';
			$menuMap['status'] = 1;
			$menuMap['rule_id'] = array('in', $ruleIds);

			$menusList = Db::name('admin_menu')->where($menuMap)->order('sort asc')->select();
		}
		if (!$menusList) {
			return null;
		}
		//处理菜单成树状
		$tree = new \com\Tree();
		$ret['menusList'] = $tree->list_to_tree($menusList, 'id', 'pid', 'child', 0, true, array('pid'));

		$ret['menusList'] = memuLevelClear($ret['menusList']);
		// 处理规则成树状
		$ret['rulesList'] = $tree->list_to_tree($rules, 'id', 'pid', 'child', 0, true, array('pid'));
		$ret['rulesList'] = rulesDeal($ret['rulesList']);
		//var_dump($ret);exit;
		return $ret;
	}


	/**
	 * 临时方法，获取菜单
	 */
	/**
	 * 获取菜单和权限
	 * @param  array   $param  [description]
	 */
	protected function getRule($u_id)
	{
		if ($u_id === 1) {
			$map['status'] = 1;
			$rules = Db::name('admin_rule')->where($map)->order('id asc')->select();
		} else {
			$groups = $this->get($u_id)->groups;
			//var_dump($groups);
			$ruleIds = [];
			foreach ($groups as $k => $v) {
				$ruleIds = array_unique(array_merge($ruleIds, explode(',', $v['rules'])));
			}
			$ruleMap['id'] = array('in', $ruleIds);
			$ruleMap['status'] = 1;
			// 重新设置ruleIds，除去部分已删除或禁用的权限。
			$rules = Db::name('admin_rule')->where($ruleMap)->select();
			foreach ($rules as $k => $v) {
				$ruleIds[] = $v['id'];
				$rules[$k]['name'] = strtolower($v['name']);
			}
			empty($ruleIds) && $ruleIds = '';
			$menuMap['status'] = 1;
			$menuMap['rule_id'] = array('in', $ruleIds);
		}

		//处理菜单成树状
		$tree = new \com\Tree();
		// 处理规则成树状
		//var_dump($rules);
		//die();
		//var_dump($tree->list_to_tree($rules, 'id', 'pid', 'child', 0, true, array('pid')));die;
		$ret['rulesList'] = $tree->list_to_tree($rules, 'id', 'pid', 'child', 0, true, array('pid'));

		$ret['rulesList'] = rulesDeal($ret['rulesList']);
		//var_dump($ret);exit;
		return $ret;
	}


	public function checkVerifyCode($verifyCode)
	{
		if (!$verifyCode) {
			$this->error = '验证码不能为空';
			return false;
		}
		$captcha = new JdeVerify(config('captcha'));
		if (!$captcha->check($verifyCode)) {
			$this->error = '验证码错误';
			return false;
		}
		return true;
	}

	/**
	 * 通过群组id获取列表
	 */
	public function getListWithDptByDid($param, $limit, $page)
	{
		$filter = ['a.id', 'structure_id','username', 'a.update_time', 'user_group', 'status'];
		$_union = $this->alias('a');
		if (isset($param['did'])) {
			$_union = $_union->join('group_user g', 'a.id = g.uid')->join('department d', 'd.dptid = g.did');
		}
		$result =     $_union
			->where($param)
			->limit($limit)
			->page($page)
			->field($filter)
			->order('status desc,a.id')
			->select();
		$count = isset($param['did']) ? $this->alias('a')->join('group_user g', 'a.id = g.uid')->where($param)->count() : $this->alias('a')->where($param)->count();
		$status_detail = ['冻结', '正常'];
		$group_detail = [1 => '管理员', 4 => '普通用户' , 16=>'超级管理员'];
		foreach ($result as $key => $value) {
			$result[$key]['update_time'] = date('Y-m-d H:i:m', $value['update_time']);
			$result[$key]['detail'] = $status_detail[$value['status']];
			$result[$key]['group_detail'] = $group_detail[$value['user_group']];
			if($user_has_sn = Model('UserHasSn')->get(['uid' => $value['id']])){
				$result[$key]['sn'] = $user_has_sn->sn;
			}else{
				$result[$key]['sn'] = "0";
			}
		}
		return [
			'list' => $result,
			'total' => $count,
			'total_page' => ceil($count / $limit)
		];
	}
}
